import axios from 'axios'
import { useAuthStore } from '@/stores/auth'
import { MessagePlugin } from 'tdesign-vue-next'

const request = axios.create({
  baseURL: '/api',
  timeout: 10000
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const authStore = useAuthStore()
    if (authStore.token) {
      config.headers.Authorization = `Bearer ${authStore.token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 401:
          MessagePlugin.error('认证失败，请重新登录')
          const authStore = useAuthStore()
          authStore.logout()
          window.location.href = '/login'
          break
        case 403:
          MessagePlugin.error('权限不足')
          break
        case 500:
          MessagePlugin.error('服务器内部错误')
          break
        default:
          MessagePlugin.error(data.error || '请求失败')
      }
    } else {
      MessagePlugin.error('网络错误，请检查网络连接')
    }
    
    return Promise.reject(error)
  }
)

export default request